<template>
    <div class="question-container">
      <el-tabs v-model="activeTab" type="card">
        <!-- 单个题目上传标签页 -->
        <el-tab-pane label="单个上传" name="single">
          <el-form
            ref="singleFormRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            class="question-form"
          >
            <!-- 原有单个上传表单内容 -->
            <el-row>
                <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item label="科目" prop="subject_id" required>
                <el-select
                v-model="formData.subject_id"
                placeholder="请选择科目"
                @change="handleSubjectChange"
                >
                <el-option
                    v-for="item in subjects"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
                </el-select>
            </el-form-item>
        </el-col>
        
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item label="章节" prop="chapter_id">
                <el-cascader
                v-model="formData.chapter_id"
                :options="chapters"
                :props="{
                    value: 'id',
                    label: 'name',
                    children: 'children',
                    checkStrictly: true,
                    emitPath: false
                }"
                placeholder="请选择章节"
                clearable
                />
            </el-form-item>
        </el-col>
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <div style="margin-top: 10px;"></div>

            <el-form-item label="难度" prop="difficulty">
                <el-rate v-model="formData.difficulty" :max="5" />
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div style="margin-top: 10px;"></div>

            <el-form-item label="题型" prop="question_type" required>
                <el-radio-group v-model="formData.question_type" @change="handleTypeChange">
                <el-radio-button :label="1">单选题</el-radio-button>
                <el-radio-button :label="2">多选题</el-radio-button>
                <el-radio-button :label="3">判断题</el-radio-button>
                <el-radio-button :label="4">填空题</el-radio-button>
                <el-radio-button :label="5">简答题</el-radio-button>
                </el-radio-group>
            </el-form-item>
        </el-col>
        
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <div style="margin-top: 10px;"></div>

            <el-form-item label="题目内容" prop="content" required>
                <el-input
                v-model="formData.content"
                type="textarea"
                :rows="3"
                placeholder="请输入题目内容"
                />
            </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.question_type <3">
            <div style="margin-top: 10px;"></div>
            
            <el-form-item
                v-if="hasOptions"
                label="题目选项"
                prop="options"
                :rules="[
                {
                    validator: validateOptions,
                    trigger: 'blur'
                }
                ]"
            >
                <div v-for="(option, index) in formData.options" :key="index" class="option-item">
                <el-checkbox
                    v-model="option.is_correct"
                    :true-label="1"
                    :false-label="0"
                    class="option-correct"
                >
                    正确
                </el-checkbox>
                <el-input
                    v-model="option.option_key"
                    placeholder="选项键"
                    class="option-key"
                    @blur="sortOptions"
                />
                <el-input
                    v-model="option.option_content"
                    placeholder="选项内容"
                    class="option-content"
                />
                <el-button
                    type="danger"
                    :icon="Delete"
                    circle
                    @click="removeOption(index)"
                />
                
                </div>
                <el-button type="primary" style="margin-bottom: 10px; margin-left: 10px;" circle :icon="Plus" @click="addOption"></el-button>
            </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <div style="margin-top: 10px;"></div>

            <el-form-item label="正确答案" prop="answer" required>
                <el-input
                v-if="!hasOptions"
                v-model="formData.answer"
                placeholder="请输入正确答案"
                />
                <el-select
                v-else-if="formData.question_type === 1"
                v-model="formData.answer"
                placeholder="请选择正确答案"
                >
                <el-option
                    v-for="option in formData.options"
                    :key="option.option_key"
                    :label="option.option_key"
                    :value="option.option_key"
                />
                </el-select>
                <el-checkbox-group
                v-else-if="formData.question_type === 2"
                v-model="formData.answers"
                >
                <el-checkbox
                    v-for="option in formData.options"
                    :key="option.option_key"
                    :label="option.option_key"
                >
                    {{ option.option_key }}
                </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div style="margin-top: 10px;"></div>

            <el-form-item label="题目解析" prop="analysis">
                <el-input
                v-model="formData.analysis"
                type="textarea"
                :rows="3"
                placeholder="请输入题目解析"
                />
            </el-form-item>
        </el-col>

        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <div style="margin-top: 10px;"></div>
            <el-form-item label="分值" prop="score">
                <el-input-number v-model="formData.score" :min="1" />
            </el-form-item>
        </el-col>


              
              <!-- 其他表单元素保持不变 -->
              <!-- ... -->
            </el-row>
            
            <div style="margin-top: 20px;"></div>
            <el-form-item>
              <el-button type="primary" @click="submitSingleForm">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
  
        <!-- 批量上传标签页 -->
        <el-tab-pane label="批量上传" name="batch">
          <el-form
            ref="batchFormRef"
            :model="batchForm"
            label-width="100px"
            class="batch-form"
          >
            <el-form-item label="模板下载">
              <el-button type="primary" @click="downloadTemplate">
                <el-icon><Download /></el-icon>下载Excel模板
              </el-button>
            </el-form-item>
            
            <el-form-item label="上传文件" prop="file" required>
              <el-upload
                class="upload-demo"
                drag
                action=""
                :auto-upload="false"
                :on-change="handleFileChange"
                :file-list="fileList"
                accept=".xlsx,.xls"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传Excel文件，大小不超过10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            
            <el-form-item label="默认科目" prop="default_subject_id">
              <el-select
                v-model="batchForm.default_subject_id"
                placeholder="请选择默认科目"
                clearable
              >
                <el-option
                  v-for="item in subjects"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="submitBatchForm"
                :loading="batchLoading"
              >
                批量导入
              </el-button>
              <el-button @click="resetBatchForm">重置</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 导入结果展示 -->
          <div v-if="importResult" class="import-result">
            <el-alert
              :title="`导入完成：成功 ${importResult.success} 条，失败 ${importResult.fail} 条`"
              :type="importResult.fail > 0 ? 'warning' : 'success'"
              show-icon
              :closable="false"
            />
            
            <el-table
              v-if="importResult.fail_list && importResult.fail_list.length > 0"
              :data="importResult.fail_list"
              border
              style="width: 100%; margin-top: 20px;"
            >
              <el-table-column prop="index" label="行号" width="80" />
              <el-table-column prop="content" label="题目内容" />
              <el-table-column prop="error" label="错误原因" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { Delete, Plus, Download, UploadFilled } from '@element-plus/icons-vue';
  import type { FormInstance, FormRules, UploadProps, UploadFile } from 'element-plus';
  import { read, utils } from 'xlsx';
  import {
    getSubjects,
    getChapterTree,
    batchCreateQuestions
  } from '/@/api/question/index';
  import type {
    QuestionDetail,
    QuestionOption,
    Subject,
    Chapter
  } from '/@/types/question';
  
  const props = defineProps<{
    initialData?: QuestionDetail;
  }>();
  
  const emit = defineEmits<{
    (e: 'submit', data: QuestionDetail): void;
    (e: 'batch-submit', data: any): void;
  }>();
  
  // 表单相关
  const singleFormRef = ref<FormInstance>();
  const batchFormRef = ref<FormInstance>();
  const activeTab = ref('single');
  const batchLoading = ref(false);
  const fileList = ref<UploadFile[]>([]);
  const importResult = ref<any>(null);
  
  // 表单数据
  const formData = ref<QuestionDetail>({
    subject_id: 0,
    chapter_id: 0,
    question_type: 1,
    difficulty: 3,
    content: '',
    answer: '',
    analysis: '',
    answers: '',
    score: 1,
    options: [
      { option_key: 'A', option_content: '', is_correct: 0 },
      { option_key: 'B', option_content: '', is_correct: 0 }
    ]
  });
  
  const batchForm = ref({
    file: null,
    default_subject_id: null
  });
  
  const subjects = ref<Subject[]>([]);
  const chapters = ref<Chapter[]>([]);
  
  const hasOptions = computed(() => {
    return [1, 2].includes(formData.value.question_type);
  });
  
  const rules = ref<FormRules>({
    subject_id: [{ required: true, message: '请选择科目', trigger: 'change' }],
    question_type: [{ required: true, message: '请选择题型', trigger: 'change' }],
    content: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
    answer: [{ required: true, message: '请输入正确答案', trigger: 'blur' }],
    file: [{ required: true, message: '请上传文件', trigger: 'blur' }]
  });
  
  // 初始化数据
  onMounted(async () => {
    if (props.initialData) {
      formData.value = JSON.parse(JSON.stringify(props.initialData));
    }
  
    try {
      const [subjectsRes, chaptersRes] = await Promise.all([
        getSubjects(),
        getChapterTree()
      ]);
      subjects.value = subjectsRes.data;
      chapters.value = chaptersRes.data;
    } catch (error) {
      console.error('初始化数据失败:', error);
    }
  });
  
  // 单个表单相关方法
  const handleSubjectChange = (subjectId: number) => {
    formData.value.chapter_id = 0;
  };
  
  const handleTypeChange = (type: number) => {
    if ([1, 2].includes(type)) {
      if (!formData.value.options || formData.value.options.length === 0) {
        formData.value.options = [
          { option_key: 'A', option_content: '', is_correct: 0 },
          { option_key: 'B', option_content: '', is_correct: 0 }
        ];
      }
      if (type === 1) {
        const correctOption = formData.value.options.find(
          (opt) => opt.is_correct === 1
        );
        formData.value.answer = correctOption
          ? correctOption.option_key
          : formData.value.options[0].option_key;
      } else {
        formData.value.answer = formData.value.options
          .filter((opt) => opt.is_correct === 1)
          .map((opt) => opt.option_key)
          .join(',');
      }
    } else {
      formData.value.options = [];
      formData.value.answer = '';
    }
  };
  
  const addOption = () => {
    if (!formData.value.options) {
      formData.value.options = [];
    }
    const nextKey = String.fromCharCode(
      65 + formData.value.options.length
    );
    formData.value.options.push({
      option_key: nextKey,
      option_content: '',
      is_correct: 0
    });
  };
  
  const removeOption = (index: number) => {
    if (formData.value.options && formData.value.options.length > 2) {
      formData.value.options.splice(index, 1);
      sortOptions();
    }
  };
  
  const sortOptions = () => {
    if (formData.value.options) {
      formData.value.options.sort((a, b) =>
        a.option_key.localeCompare(b.option_key)
      );
    }
  };
  
  const validateOptions = (
    rule: unknown,
    value: QuestionOption[],
    callback: (error?: Error) => void
  ) => {
    if (!hasOptions.value) {
      callback();
      return;
    }
  
    if (!value || value.length < 2) {
      callback(new Error('至少需要两个选项'));
      return;
    }
  
    const hasCorrect = value.some((opt) => opt.is_correct === 1);
    if (!hasCorrect) {
      callback(new Error('至少需要一个正确选项'));
      return;
    }
  
    const keys = new Set<string>();
    const contents = new Set<string>();
  
    for (const opt of value) {
      if (!opt.option_key.trim()) {
        callback(new Error('选项键不能为空'));
        return;
      }
      if (!opt.option_content.trim()) {
        callback(new Error('选项内容不能为空'));
        return;
      }
      if (keys.has(opt.option_key)) {
        callback(new Error('选项键不能重复'));
        return;
      }
      if (contents.has(opt.option_content)) {
        callback(new Error('选项内容不能重复'));
        return;
      }
      keys.add(opt.option_key);
      contents.add(opt.option_content);
    }
  
    callback();
  };
  
  const submitSingleForm = async () => {
    try {
      await singleFormRef.value?.validate();
      
      if (formData.value.question_type === 2 && Array.isArray(formData.value.answers)) {
        formData.value.answer = formData.value.answers.join(',');
      }
      
      emit('submit', formData.value);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };
  
  const resetForm = () => {
    singleFormRef.value?.resetFields();
    if (hasOptions.value) {
      formData.value.options = [
        { option_key: 'A', option_content: '', is_correct: 0 },
        { option_key: 'B', option_content: '', is_correct: 0 }
      ];
    }
  };
  
  // 批量上传相关方法
  const handleFileChange: UploadProps['onChange'] = (file) => {
    batchForm.value.file = file.raw;
  };
  
  const downloadTemplate = () => {
    // 这里实现下载Excel模板的逻辑
    const templateUrl = '/templates/question_import_template.xlsx';
    const link = document.createElement('a');
    link.href = templateUrl;
    link.download = '题目导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
  
  const parseExcelToJson = (file: File): Promise<any[]> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = read(data, { type: 'array' });
          const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
          const jsonData = utils.sheet_to_json(firstSheet);
          
          // 转换数据格式
          const questions = jsonData.map((item: any) => {
            const question: any = {
              subject_id: item.subject_id || batchForm.value.default_subject_id,
              chapter_id: item.chapter_id || 0,
              question_type: parseInt(item.question_type) || 1,
              difficulty: parseInt(item.difficulty) || 3,
              content: item.content || '',
              answer: item.answer || '',
              analysis: item.analysis || '',
              score: parseInt(item.score) || 1,
              status: 1
            };
            
            // 处理选择题选项
            if ([1, 2].includes(question.question_type)) {
              question.options = [];
              for (let i = 1; i <= 6; i++) {
                if (item[`option_key_${i}`] && item[`option_content_${i}`]) {
                  question.options.push({
                    option_key: item[`option_key_${i}`],
                    option_content: item[`option_content_${i}`],
                    is_correct: item[`is_correct_${i}`] ? 1 : 0,
                    sort: i
                  });
                }
              }
            }
            
            return question;
          });
          
          resolve(questions);
        } catch (error) {
          reject(error);
        }
      };
      
      reader.onerror = (error) => {
        reject(error);
      };
      
      reader.readAsArrayBuffer(file);
    });
  };
  
  const submitBatchForm = async () => {
    try {
      await batchFormRef.value?.validate();
      
      if (!batchForm.value.file) {
        throw new Error('请先上传文件');
      }
      
      batchLoading.value = true;
      importResult.value = null;
      
      // 解析Excel文件
      const questions = await parseExcelToJson(batchForm.value.file);
      
      // 调用批量导入API
      const res = await batchCreateQuestions({
        questions,
        default_subject_id: batchForm.value.default_subject_id
      });
      
      importResult.value = res.data;
      fileList.value = [];
      batchForm.value.file = null;
      
      // 触发事件通知父组件
      emit('batch-submit', res.data);
    } catch (error) {
      console.error('批量导入失败:', error);
      ElMessage.error('批量导入失败: ' + error.message);
    } finally {
      batchLoading.value = false;
    }
  };
  
  const resetBatchForm = () => {
    batchFormRef.value?.resetFields();
    fileList.value = [];
    importResult.value = null;
    batchForm.value = {
      file: null,
      default_subject_id: null
    };
  };
  
  defineExpose({
    submitSingleForm,
    submitBatchForm
  });
  </script>
  
  <style scoped>
  .question-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .question-form,
  .batch-form {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
  }
  
  .upload-demo {
    width: 100%;
  }
  
  .import-result {
    margin-top: 20px;
  }
  
  .option-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .option-correct {
    min-width: 70px;
    margin-right: 10px;
  }
  
  .option-key {
    width: 80px;
    margin-right: 10px;
  }
  
  .option-content {
    flex: 1;
    margin-right: 10px;
  }
  </style>